import { createNewCom } from '@/utils/index'
export default {
  setSelectedCom({ commit }, payload) {
    let { comData, childWraper } = payload
    //清除上一个元素的选中
    commit('setCurrentComFocus', false)
    //更新选中元素
    commit('setCurrentCom', comData)
    //更新选中元素的父flex的children属性(用于删除)
    commit('setCurrentComWraper', childWraper || null)
    //选中选中元素聚焦
    commit('setCurrentComFocus', true)
  },
  addChildFlexBox({ state }) {
    const children = state.currentCom.children
    let isEmpty = children.length === 0
    let newCom = createNewCom('FlexBox', isEmpty)
    children.push(...newCom)
  },
  deleteCom({ state, commit }) {
    let comId = state.currentCom.id
    //顶层框架组件删除
    if (!state.currentComWraper) {
      const newView = state.centerView.filter((el) => el.id !== comId)
      commit('setCenterView', newView)
    } else {
      //子组件删除
      let { currentComWraper } = state
      currentComWraper.children = currentComWraper.children.filter(
        (el) => el.id !== comId
      )
      const { children } = currentComWraper
      if (children.length === 1 && children[0].comName === 'FlexBox') {
        currentComWraper.children = currentComWraper.children[0].children
      }
    }
  },
  dropCom2FlexBox({ state, commit }, { offsetY, offsetX }) {
    let newCom
    const {
      id,
      offsetY: comY,
      offsetX: comX,
      dragedCom,
      childWraper,
    } = state.dragedComInfo
    if (id) {
      newCom = createNewCom(id)[0]
    } else {
      newCom = dragedCom
      let comId = dragedCom.id
      childWraper.children = childWraper.children.filter(
        (el) => el.id !== comId
      )
    }
    if (state.dragMode === 'absolute') {
      let top = offsetY - comY > 0 ? offsetY - comY : 0
      let left = offsetX - comX > 0 ? offsetX - comX : 0
      newCom.style.left = left + 'px'
      newCom.style.top = top + 'px'
    }
    const { children } = state.currentCom
    children.push(newCom)
    //清除上一个元素的选中
    commit('setCurrentComFocus', false)
  },
}
